package com.cucn.ingmall.order.listener;

import com.cucn.common.constant.order.OrderRabbitMqConstant;
import com.cucn.ingmall.order.entity.OrderEntity;
import com.cucn.ingmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 订单关闭的消息队列监听器
 *
 * @author KouChaoJie
 * @since: 2022/1/27 14:10
 */
@Service
@Slf4j
@RabbitListener(queues = OrderRabbitMqConstant.ORDER_RELEASE_ORDER_QUEUE)
public class OrderCloseListener {

    @Resource
    private OrderService orderService;

    @RabbitListener(queues = OrderRabbitMqConstant.ORDER_RELEASE_ORDER_QUEUE)
    public void listener(OrderEntity order, Channel channel, Message message) throws IOException {
        log.info("收到过期的消息,准备关闭订单:{},发送时间:{}", order.getOrderSn(), order.getCreateTime());

        try {
            orderService.closeOrder(order);
            //手动调用支付宝收单

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("消息消费成功,订单成功关单");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("关单失败,请根据异常信息检查业务逻辑");
            //打回队列,重新消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
